package com.soft.support.impl;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;

import com.soft.admin.common.ElementConst;
import com.soft.admin.service.impl.BaseServiceImpl;
import com.soft.model.Action;
import com.soft.model.RoleColumn;
import com.soft.model.UserColumn;
import com.soft.model.UserRole;
import com.soft.support.UserSecurityService;

public class UserSecurityServiceImpl extends BaseServiceImpl implements UserSecurityService {
	
	public User getLoginUserInfo(String username) {
		com.soft.model.User user = (com.soft.model.User)this.getBaseDao().findUniqueByProperty(
				com.soft.model.User.class, "username", username);
		if (user == null || !user.getEnabled()) {
			return null;
		}
		Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);  
        User userdetail = new User(
        		username, user.getPassword(), user.getEnabled(), true, true, true, grantedAuths);
		return userdetail;
	}
	
	/**
	 * 取得用户的权限.  
	 */
    private Set<GrantedAuthority> obtionGrantedAuthorities(com.soft.model.User user) {  
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();  
        Set<UserRole> urs = user.getUserRoles();
        for (UserRole ur : urs) {
        	Set<RoleColumn> rcs = ur.getRole().getRoleColumns();
        	for (RoleColumn rc : rcs) {
        		Action action = rc.getColumn().getAction();
        		if (action != null) {
        			authSet.add(new GrantedAuthorityImpl(action.getCode()));
        		}
        	}
        }
//        Set<Role> roles = user.getRoles();  
//        for (Role role : roles) {
//        	Set<ActionColumn> acs = role.getActionColumns();
//        	for (ActionColumn ac : acs) {
//        		if (ac.getAction() != null) {
//        			authSet.add(new GrantedAuthorityImpl(ac.getAction().getCode()));
//        		}
//        	}
//        }
        Set<UserColumn> ucs = user.getUserColumns();
        for (UserColumn uc : ucs) {
        	GrantedAuthority gay = new GrantedAuthorityImpl(uc.getActionColumn().getAction().getCode());
        	if (authSet.contains(gay)) {
        		if (!uc.getEnabled()) authSet.remove(gay);
        	} else {
        		if (uc.getEnabled()) authSet.add(gay);
        	}
        }
        //默认授予权限
        for(String own : ElementConst.OWNACTION) {
        	authSet.add(new GrantedAuthorityImpl(own));
        }
        return authSet;  
    }

}
